package moodish.client;

import javax.swing.JOptionPane;

import moodish.comm.ClientComm;
import moodish.comm.ClientSideMessage;
import moodish.comm.ClientSideMessage.Type;

public class MessageReader implements Runnable {

	private GUI gui;
	private ClientComm clientComm;

	public MessageReader(GUI gui, ClientComm clientComm) {
		this.gui = gui;
		this.clientComm = clientComm;
	}

	/**
	 * Implements the infinite cycle that reads every incoming message
	 */
	@Override
	public void run() {
		while (true) {
			ClientSideMessage msg = clientComm.getNextMessage();
			if (msg != null) {
				readMsg(msg);
			} else {
				gui.connectionLost();
				return;
			}
		}
	}

	/**
	 * Interprets the message and calls the appropriate GUI methods and/or
	 * displays the relevant information to the user
	 * 
	 * @param msg
	 */
	private void readMsg(ClientSideMessage msg) {
		ClientSideMessage.Type type = msg.getType();
		String payLoad = msg.getPayload();
		String senderName = msg.getSendersNickname();

		switch (type) {
		case CONNECTED:
			if (!payLoad.equals(gui.getUserNickName()))
				gui.userConnected(payLoad);
			break;
		case DISCONNECTED:
			if (payLoad.equals(gui.getUserNickName()))
				gui.connectionLost();
			else
				gui.userDisconnected(payLoad);
			break;
		case MOODISH_MESSAGE:
			gui.setMood(senderName, payLoad);
			break;
		case FRIENDSHIP:
			JOptionPane.showMessageDialog(gui.getJFrame(), "The user "
					+ payLoad + " is now your friend");
			break;
		case UNFRIENDSHIP:
			JOptionPane.showMessageDialog(gui.getJFrame(), "The user "
					+ payLoad + " is no longer your friend");
			break;
		case ERROR:
			switch (payLoad) {
			case "Nickname duplicated. Please pick another one":
				gui.connectionLost();
				JOptionPane.showMessageDialog(gui.getJFrame(), payLoad);
				break;
			}
		default:
			break;
		}

	}
}